<?php

namespace kitego\exception;

use kitego\enum\ApiCodeEnum;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Request;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class KitegoBaseExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        if (!$this->isIgnoreReport($exception)) {
            try {
                $data = [
                    'code' => $this->getCode($exception),
                    'message' => $this->getMessage($exception),
                    'file' => $exception->getFile(),
                    'line' => $exception->getLine(),
                ];

                // 日志内容
                $log = [
                    '访问者ID: ' . request()->adminId ?? request()->userId,
                    '客户IP: ' . request()->ip(),
                    '耗时（毫秒）:' . ceil(ms_time() - (request()->time(true) * 1000)),
                    '请求类型: ' . request()->rule()->getMethod(),
                    '应用: ' . str_replace("/", "", request()->rootUrl()),
                    '路由: ' . request()->baseUrl(),
                    '请求参数: ' . json_encode(request()->param(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                    '报错数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
                ];

                kg_file_put_contents('exception', $log);
            } catch (\Throwable $e) {
                kg_file_put_contents('exception', [$e->getMessage()]);
            }
        }
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 添加自定义异常处理机制
        if ($e instanceof HttpResponseException || $e instanceof HttpException) {
            return parent::render($request, $e);
        }

        // 参数验证错误
        if ($e instanceof ValidateException) {
            return fail($e->getError());
        }

        $massageData = env('app_debug', false) ? [
            'code' => $e->getCode(),
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTrace(),
            'previous' => $e->getPrevious(),
        ] : [];
        $message = $e->getMessage();

        return fail($message, ApiCodeEnum::FAIL, $massageData);
    }
}
